package com.myflink.day02;

import com.myflink.bean.WaterSensor;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Shelly An
 * @create 2020/9/16 16:04
 */
public class Transform_RichMapFuction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //有界，open一次，close两次；无界 open一次 close一次
        DataStreamSource<String> inputDS = env.readTextFile("input/sensor-data.log");

        SingleOutputStreamOperator<WaterSensor> sensorDS = inputDS.map(new MyRichMapFunction());
        sensorDS.print();


        env.execute();
    }

    /**
     * 继承RichMapFunction 指定输入的类型，返回的类型
     * 重写Map方法
     * 提供了open，close 生命周期管理方法，常用于连接对象、如mysql、数据流
     * 能够获取 运行时 上下文对象 getRuntimeContext =》 可以获取 状态、任务信息等环境信息
     */
    public static class MyRichMapFunction extends RichMapFunction<String, WaterSensor> {
        @Override
        public WaterSensor map(String value) throws Exception {
            String[] datas = value.split(",");
            return new WaterSensor(getRuntimeContext().getTaskName() +datas[0],Long.valueOf(datas[1]),Integer.valueOf(datas[2]));
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open....");
        }

        @Override
        public void close() throws Exception {
            System.out.println("close....");
        }
    }
}
